package com.java.business.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.business.dao.CourseDao;
import com.java.business.entity.Course;
import com.java.business.entity.CourseContent;
import com.java.business.service.CourseCategoryService;
import com.java.business.service.CourseContentService;
import com.java.business.service.CourseService;
import com.java.common.dto.SortDto;
import com.java.common.utils.PageUtils;
import com.java.common.utils.Query;
import com.java.common.utils.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service("courseService")
public class CourseServiceImpl extends ServiceImpl<CourseDao, Course> implements CourseService {
    @Autowired
    private CourseCategoryService courseCategoryService;
    @Autowired
    private CourseContentService courseContentService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<Course> page = this.page(
                new Query<Course>().getPage(params),
                // 拼接查询条件
                new LambdaQueryWrapper<Course>()
        );

        return new PageUtils(page);
    }

    @Override
    public void updateTime(String courseId) {
        this.baseMapper.updateTime(courseId);
    }

    @Override
    @Transactional
    public void updateOrSave(Course course) {
        if (StrUtil.isNotBlank(course.getId())) {
            this.updateById(course);
        } else {
            course.setId(UuidUtil.getShortUuid());
            this.save(course);
        }

        // 批量保存课程分类
        courseCategoryService.saveBatchCourseCategory(course);
    }

    /**
     * 查询课程内容
     */
    @Override
    public CourseContent findContent(String id) {
        return courseContentService.getById(id);
    }

    /**
     * 保存课程内容
     */
    @Override
    public void saveContent(CourseContent courseContent) {
        courseContentService.saveOrUpdate(courseContent);
    }

    @Override
    public void sort(SortDto sortDto) {
        // 修改当前记录的排序值
        this.baseMapper.updateSort(sortDto);

        // 如果排序值变大
        if (sortDto.getNewSort() > sortDto.getOldSort()) {
            this.baseMapper.moveSortsForward(sortDto);
        }

        // 如果排序值变小
        if (sortDto.getNewSort() < sortDto.getOldSort()) {
            this.baseMapper.moveSortsBackward(sortDto);
        }
    }

}